package com.changgou.oauth.service.impl;

import com.changgou.oauth.service.UserLoginService;

import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Map;

/**
 * @ClassName UserLoginServiceImpl
 * @Description
 * @Author Mr.L
 * @Date 13:30 2019/11/22
 * @Version 2.1
 **/
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    @Override
    public AuthToken login( String username, String password, String clientId, String clientSecret,String grant_type) {
        try {
            //指定授权的url地址
            ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");
            String uri = serviceInstance.getUri().toString();
            String url = uri + "/oauth/token";


            //封装请求数据
            byte[] encode = Base64.getEncoder().encode((clientId + ":" + clientSecret).getBytes());

            String clientEncode = new String(encode, "UTF-8");
            LinkedMultiValueMap headers = new LinkedMultiValueMap();
            //
            headers.add("Authorization","Basic " + clientEncode);
            headers.add("haha","hehe");
            LinkedMultiValueMap body = new LinkedMultiValueMap();
            body.add("grant_type",grant_type);
            body.add("username",username);
            body.add("password",password);
            HttpEntity requestEntity = new HttpEntity(body, headers);

            //发送请求
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);

            //响应结果处理
            Map<String, String> map = responseEntity.getBody();

            AuthToken authToken = new AuthToken();
            authToken.setAccessToken(map.get("access_token").toString());
            authToken.setRefreshToken(map.get("refresh_token").toString());
            authToken.setJti(map.get("jti").toString());
            return authToken;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
